package com.qf.fcy.youshare.utils;

import android.content.Context;
import android.os.Environment;
import android.widget.Toast;

import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created with IntelliJ IDEA.
 * User: Alex[FR]
 * Date: 2015/2/4
 * Email: alex_fcy@163.com
 */
public class CommonUtils {
    public static void toast(Context context, String toastMsg) {
        Toast.makeText(context, toastMsg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 在卸载应用后，会自动删除该文件夹
     *
     * @param context
     * @param uniqueName 保存文件夹名称
     * @return
     */
    public static File getDiskCacheDir(Context context, String uniqueName) {
        String cachePath = null;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)
                || !Environment.isExternalStorageRemovable()) {
            cachePath = context.getExternalCacheDir().getPath();
        } else { // 内存卡不存在,获取应用地址
            cachePath = context.getCacheDir().getPath();
        }
        File cacheFile = new File(cachePath + File.separator + uniqueName);
        // 如果文件夹不存在，则创建
        if (!cacheFile.exists()) {
            cacheFile.mkdirs();
        }
        return cacheFile;
    }

    /**
     * @param url 指定的任意字符串
     * @return 指定字符串通过md5运算并转化为字符串，如果url为null或长度为0，则返回null
     */
    public static String urlMDToString(String url) {
        String result = null;
        if (url != null && url.length() > 0) {
            try {
                MessageDigest md5 = MessageDigest.getInstance("MD5");
                md5.update(url.getBytes());
                byte[] tar = md5.digest();
                StringBuilder sb = new StringBuilder("");
                for (byte b : tar) {
                    int h = (b >> 4) & 15;
                    int l = b & 15;
                    // 因为4位二进制数最大为1111，即15
                    sb.append(Integer.toHexString(h)).append(
                            Integer.toHexString(l));
                }
                result = sb.toString();

            } catch (NoSuchAlgorithmException e) {
                result = String.valueOf(url.hashCode());
                e.printStackTrace();
            }
        }

        return result;
    }
}
